package com.foreknow.framework;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.处理字符编码
        //设置从服务器端向客户端返回的内容的类型   MIME类型：text/html
        response.setContentType("application/json;charset=utf-8");
        //客户端向服务器端请求和响应的编码格式(否则会产生乱码)  默认：iOS8859-1
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        //2.获取客户端发送的请求路径(URL的部分请求路径)
        String path = request.getServletPath();//
        //3.根据获取到的路径得到类名和方法名
        String className = path.substring(1,path.lastIndexOf("/"));
        String methodName = path.substring(path.lastIndexOf("/")+1);
        //4.通过反射Class.forName()获取到Controller中类的信息
        try {
            Class clazz = Class.forName("com.foreknow.controller."+className);
            //将获取到的类转换为对象
            Object controller = clazz.newInstance();
            //5.获取到方法
            Method method = clazz.getMethod(methodName,new Class[]{HttpServletRequest.class});
            //6.调用方法
            Object result = method.invoke(controller, new Object[]{request});
            //7.将结果result以JSON的数据格式响应给客户端浏览器
            ObjectMapper objectMapper = new ObjectMapper();
            out.print(objectMapper.writeValueAsString(result));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
